<template>
  <div class='add_container'>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-alert title="添加商品信息" type="info" show-icon :closable="false" center></el-alert>
      <el-steps :active="activeIndex - 0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px" label-position="top">
        <el-tabs tab-position="left" v-model="activeIndex" :before-leave="beforeTabLeave" @tab-click="tabClicked">
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader v-model="addForm.goods_cat" :options="cateList" :props="cateProps" expandTrigger="hover"
                @change="handleChange">
              </el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item v-for="item in manyTableData" :key="item.attr_id" :label="item.attr_name">
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox :label="item" v-for="item,i in item.attr_vals" :key="i" border></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item v-for="item in onlyTableData" :key="item.attr_id" :label="item.attr_name">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload :action="uploadUrl" :headers="headerObj" :on-preview="handlePreview" :on-remove="handleRemove"
              list-type="picture" :on-success="handleSuccess">
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor v-model="addForm.goods_introduce" ref="myQuillEditor"></quill-editor>
            <el-button type="primary" style="margin-top: 15px" @click="addGoods">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <el-dialog title="图片预览" :visible.sync="previewVisible" width="50%">
      <img :src="previewFilePath" alt="" class="previewImg">
    </el-dialog>
  </div>
</template>

<script>
import goods from '@/api/goods'
import _ from 'lodash'

export default {
  name: 'MyAdd',
  data () {
    return {
      activeIndex: '0',
      cateList: [],
      cateProps: {
        label: 'cat_name',
        value: 'cat_id',
        children: 'children'
      },
      addForm: {
        goods_name: '',
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        goods_cat: [],
        pics: [],
        goods_introduce: '',
        attrs: []
      },
      addFormRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' }
        ],
        goods_cat: [
          { required: true, message: '请选择商品分类', trigger: 'change' }
        ]
      },
      manyTableData: [],
      onlyTableData: [],
      uploadUrl: 'http://localhost:8888/api/private/v1/upload',
      // 添加请求头
      headerObj: {
        Authorization: sessionStorage.getItem('token')
      },
      previewFilePath: '',
      previewVisible: false
    }
  },
  components: {},
  methods: {
    // 1.获取分类
    async getCateList () {
      const { data: res } = await goods.getCategories({})
      if (res.meta.status === 200) {
        this.cateList = res.data
      } else {
        this.$message.error(res.meta.msg)
      }
    },

    // 2.级联选择器发生改变
    handleChange () {
      if (this.addForm.goods_cat.length !== 3) {
        this.addForm.goods_cat = []
        this.$message.error('请选择三级分类!')
      }
    },

    // 3.tab标签页离开
    beforeTabLeave (newVlaue, oldValue) {
      if (oldValue === '0' && this.addForm.goods_cat.length !== 3) {
        this.$message.error('请先选择商品分类')
        return false
      }
    },

    // 4.点击切换tab页
    async tabClicked () {
      if (this.activeIndex === '1') {
        // 获取动态参数
        const { data: res } = await goods.getParamList(this.cateId, 'many')
        if (res.meta.status === 200) {
          res.data.forEach(item => {
            item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
          })
          this.manyTableData = res.data
        } else {
          this.$message.error(res.meta.msg)
        }
      } else if (this.activeIndex === '2') {
        // 获取静态属性
        const { data: res } = await goods.getParamList(this.cateId, 'only')
        if (res.meta.status === 200) {
          this.onlyTableData = res.data
        } else {
          this.$message.error(res.meta.msg)
        }
      }
    },

    // 5.处理图片预览效果
    handlePreview (file) {
      this.previewFilePath = file.response.data.url
      this.previewVisible = true
    },
    // 6.处理移除图片操作
    handleRemove (file) {
      const filePath = file.response.data.tmp_path
      const index = this.addForm.pics.findIndex(x => x.pic === filePath)
      this.addForm.pics.splice(index, 1)
    },
    // 7.监听图片上传成功
    handleSuccess (response) {
      // 7.1得到图片对象
      const picInfo = { pic: response.data.tmp_path }
      this.addForm.pics.push(picInfo)
    },
    // 8.确认添加商品
    addGoods () {
      this.$refs.addFormRef.validate(async valid => {
        if (valid) {
          // 会出错，级联选择器要的是数组
          // this.addForm.goods_cat = this.addForm.goods_cat.join(',')
          // 进行深拷贝
          const form = _.cloneDeep(this.addForm)
          form.goods_cat = form.goods_cat.join(',')
          // 处理动态参数，静态属性
          this.manyTableData.forEach(item => {
            const newInfo = {
              attr_id: item.attr_id,
              attr_value: item.attr_vals.join(' ')
            }
            this.addForm.attrs.push(newInfo)
          })
          this.onlyTableData.forEach(item => {
            const newInfo = {
              attr_id: item.attr_id,
              attr_value: item.attr_vals
            }
            this.addForm.attrs.push(newInfo)
          })
          form.attrs = this.addForm.attrs
          // 执行添加
          const { data: res } = await goods.addGoods(form)
          if (res.meta.status === 201) {
            this.$message.success(res.meta.msg)
            this.activeIndex = '5'
            this.$router.push('/goods')
          } else {
            this.$message.error(res.meta.msg)
          }
        } else {
          return this.$message.error('请填写必要的表单项!')
        }
      })
    }
  },
  computed: {
    cateId () {
      if (this.addForm.goods_cat.length === 3) {
        return this.addForm.goods_cat[2]
      }
      return null
    }

  },
  created () {
    this.getCateList()
  },
  mounted () { }
}
</script>

<style lang='less' scoped>
.el-breadcrumb {
  line-height: 50px;
}

.el-steps {
  margin: 15px 100px;
}

/deep/ .el-step__title {
  font-size: 15px;
}

.el-checkbox {
  margin: 0 5px 0 0 !important;
}

.previewImg {
  width: 100%;
}
</style>
